package com.wkbb.sports.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.wkbb.common.base.BaseController;
import com.wkbb.common.constants.RedisKeyConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.*;
import com.wkbb.common.handler.JsonUtil;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.common.utils.MD5Util;
import com.wkbb.sports.dto.LekangResultDto;
import com.wkbb.sports.feign.BasicFeignService;
import com.wkbb.sports.model.LekangLogon;
import com.wkbb.sports.model.LekangTest;
import com.wkbb.sports.service.LekangService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@Api(description = "乐康主机使用")
@RequestMapping("/myJavaWebTemplate/publicControlle")
@Slf4j
public class LekangController extends BaseController {

    @Autowired
    private BasicFeignService basicFeignService;
    @Autowired
    private LekangService lekangService;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @ApiOperation(value = "获取测试计划")
    @RequestMapping(value = "/getLogonDataBaseBatch", method = RequestMethod.POST)
    public LekangResultDto<?> getLogonDataBaseBatch(@RequestBody JSONObject json) {
        log.info("getLogonDataBaseBatch:"+json.toString());
        String username = json.getString("schoolId");
        String password = json.getString("password");
        if (username != null && password != null){
            ResultDTO<List<UserDto>> userResultDTO  = basicFeignService.loginByPwd(username, MD5Util.getMD5Code(password));
            if (userResultDTO.isSuccess() && userResultDTO.getData()!= null && !userResultDTO.getData().isEmpty() ){
                List<RoleTypeJsonDto> roleType = JsonUtil.jsonToList(JsonUtil.objectToJson(userResultDTO.getData().get(0).getRoleType()),RoleTypeJsonDto.class);
//                log.info("=================================================================roleType:{}",JsonUtil.stringify(roleType));
                if (!roleType.isEmpty())
                {
                    Long orgId = roleType.get(0).getOrgId();
                    ResultDTO<List<ClassInfo>> resultDTO = basicFeignService.getClassListByOrg(orgId);
                    List<ClassInfo> classInfoDtos = resultDTO.getData();
                    if (resultDTO.isSuccess() && classInfoDtos != null){
                        LekangResultDto<JSONArray> resultDto = new LekangResultDto<>(true);
                        JSONArray jsonArray = new JSONArray();
                        for (ClassInfo classInfoDto : classInfoDtos){
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("name",classInfoDto.getClassName());
                            jsonObject.put("id",classInfoDto.getId());
                            jsonArray.add(jsonObject);
                        }
                        resultDto.setData(jsonArray);
                        return resultDto;
                    }
                }
            }
        }
        return new LekangResultDto<>(false);
    }

    @ApiOperation(value = "登录具体的测试计划")
    @RequestMapping(value = "/logonDataBaseBatch", method = RequestMethod.POST)
    public LekangResultDto<T> logonDataBaseBatch(@RequestBody JSONObject json) {
        String redisKey = RedisKeyConstant.SPORTS + "getLogonDataBaseBatch:"+json.toString();
        EmployeeInfoDto emloyee;
        emloyee = (EmployeeInfoDto)redisTemplateUtil.get(redisKey);
        if (emloyee == null) {
            String username = json.getString("userName");
            String password = json.getString("userPassword");
            if (username != null && password != null){
                ResultDTO<EmployeeInfoDto> employeeInfoDtoResultDTO = basicFeignService.getEmloyeeByPwd(username, MD5Util.getMD5Code(password));
                if (employeeInfoDtoResultDTO.isSuccess() ){
                    emloyee = employeeInfoDtoResultDTO.getData();
                    redisTemplateUtil.set(redisKey ,emloyee,12, TimeUnit.HOURS);
                }
            }
        }
        if (emloyee != null) {
            Long dataBaseBatchName = json.getLong("dataBaseBatchName");
            LekangLogon lekangLogon = new LekangLogon();
            lekangLogon.setClassId(dataBaseBatchName);
            lekangLogon.setUserId(emloyee.getUserId());
            lekangService.putLekangLogon(lekangLogon);
            return new LekangResultDto<>(true);
        }
        return new LekangResultDto<>(false);
    }

    @ApiOperation(value = "下载对应批次测试人员")
    @RequestMapping(value = "/getDataBaseBatchPersonInfo", method = RequestMethod.POST)
    public LekangResultDto<String> getDataBaseBatchPersonInfo(@RequestBody JSONObject json) {
//        log.info("getDataBaseBatchPersonInfo:"+json.toString());
        // 写到服务器上
        LekangResultDto<String> resultDto = new LekangResultDto<>(true);
        resultDto.setResmsg("http://qiniu.childrenonline.cn/LekangStu-1637664707215.xls");
        resultDto.setData("");
        log.info("resultDto:"+ JsonUtil.stringify(resultDto));
        return resultDto;
//        Long classId = json.getLong("dataBaseBatchName");
//        ResultDTO<List<StudentInfoDto>> resultDTO = basicFeignService.getStudentList(null,classId);
//        if (resultDTO.isSuccess()){
//            List<StudentInfoDto> studentInfoDtos = resultDTO.getData();
//            List<LekangStu> stuList = new ArrayList<>();
//            for (StudentInfoDto item : studentInfoDtos){
//                LekangStu lekangStu = new LekangStu();
////                lekangStu.setClassId(classId);
////                lekangStu.setClassName(item.getClassName());
////                lekangStu.setGradeId(item.getId());
////                lekangStu.setOrgName(item.getOrgName());
//                lekangStu.setTestId(item.getId());
//
//                lekangStu.setSex(item.getSex());
//                lekangStu.setStudentId(item.getId());
//                lekangStu.setStudentName(item.getName());
//                stuList.add(lekangStu);
//            }
//            ByteArrayOutputStream out = null;
//            try {
//                Date now = new Date();
//                String fileName = "LekangStu-" + now.getTime()+".xls";
//                //写到服务器上
////                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
////                String path = request.getSession().getServletContext().getRealPath("") + "/LekangStu-" + now.getTime()+".xls";
//                //写到服务器上 （这种测试过，在本地可以，放到linux服务器就不行）
////                String path =  this.getClass().getClassLoader().getResource("").getPath()+"/LekangStu-" + now.getTime()+".xls";
//                out = new ByteArrayOutputStream();
//
//                ExcelWriter writer = new ExcelWriter(null,out, ExcelTypeEnum.XLS,true);
//                //写第一个sheet, sheet1  数据全是List<String> 无模型映射关系
//                Sheet sheet1 = new Sheet(1,0, LekangStu.class);
//
//                writer.write(stuList, sheet1);
//                writer.finish();
//
//                byte[] bytes = out.toByteArray();
//                String fileUrl = QiniuUtil.getInstance().put(bytes,fileName);
//                LekangResultDto<String> resultDto = new LekangResultDto<>(true);
//                resultDto.setResmsg(fileUrl);
//                resultDto.setData("");
//                log.info("resultDto:"+ JsonUtil.stringify(resultDto));
//                return resultDto;
//            } catch (Exception e) {
//                e.printStackTrace();
//            } finally {
//                try {
//                    out.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return new LekangResultDto<>(false);
    }

    @ApiOperation(value = "上传测试数据")
    @RequestMapping(value = "/sendPersonTestDataToDataBaseBatch", method = RequestMethod.POST)
    public LekangResultDto<T> sendPersonTestDataToDataBaseBatch(@RequestBody JSONObject json) {
        log.info("sendPersonTestDataToDataBaseBatch:"+json.toString());
        Long classId = json.getLong("dataBaseBatchName");
        JSONArray jsonArray = json.getJSONArray("personTestDatas");
        //过滤重复数据
        Set<LekangTest> set = new TreeSet<>(Comparator.comparing(o -> o.getStudentId() + ";" + o.getScore()));
        for (int i =0 ;i< jsonArray.size();i++){
            JSONObject item = jsonArray.getJSONObject(i);
            LekangTest lekangTest = new LekangTest();
            lekangTest.setClassId(classId);
            lekangTest.setStudentId(item.getLong("testID"));
            lekangTest.setTestItemID(item.getInteger("testItemID"));
            lekangTest.setScore(item.getDouble("testScore"));
            lekangTest.setStatus(0);
            set.add(lekangTest);
        }
        try {
            lekangService.insertBatch(new ArrayList<>(set));
            return new LekangResultDto<>(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new LekangResultDto<>(false);
    }

    @ApiOperation(value = "测试人员的总测试成绩以及各个项目的测试成绩")
    @RequestMapping(value = "/getOnePersonTestScoreFromDataBaseBatch", method = RequestMethod.POST)
    public LekangResultDto<T> getOnePersonTestScoreFromDataBaseBatch(@RequestBody JSONObject json) {
        log.info("getOnePersonTestScoreFromDataBaseBatch:"+json.toString());
        return new LekangResultDto<>(true);
    }

}
